<template>
  <div>
    <el-backtop></el-backtop>
    <el-row :gutter="10">
      <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
        <el-carousel height="400px">
          <el-carousel-item
            v-for="(item, index) in goodsDetail.image.images"
            :key="index"
          >
            <el-image :src="item" style="width: 100%; height: 400px"></el-image>
          </el-carousel-item>
        </el-carousel>
        <video controls="controls" width="380" style="margin-top: 20px">
          <source :src="goodsDetail.mainVedio" type="video/mp4" />
        </video>
      </el-col>
      <el-col :xs="16" :sm="16" :md="16" :lg="16" :xl="16">
        <el-row>
          <h3>{{ goodsDetail.subject }}</h3>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="4">
            <el-image
              :src="goodsDetail.skuInfos[form.edu].attributes[0].skuImageUrl"
              style="width: 100px; height: 100px"
            ></el-image>
          </el-col>
          <el-col :span="10">
            edu：
            <el-select v-model="form.edu" placeholder="请选择">
              <el-option
                v-for="(item, index) in goodsDetail.skuInfos"
                :key="index"
                :label="
                  item.attributes[0].attributeName +
                  ':' +
                  item.attributes[0].attributeValue
                "
                :value="index"
              >
                <span v-for="(i, index) in item.attributes" :key="index"
                  >{{ i.attributeName }}:{{ i.attributeValue }}</span
                >
                <span>价格：{{ item.consignPrice }}</span>
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="10">
            报价时该规格的单价：
            <span style="color: red"
              >¥ {{ goodsDetail.skuInfos[form.edu].price }}</span
            >
            <br />分销基准价：
            <span style="color: red"
              >¥ {{ goodsDetail.skuInfos[form.edu].consignPrice }}</span
            >
            <br />建议零售价：
            <span style="color: red"
              >¥ {{ goodsDetail.skuInfos[form.edu].retailPrice }}</span
            >
            <br />CPS建议价（单位：元）：
            <span style="color: red"
              >¥ {{ goodsDetail.saleInfo.cpsSuggestPrice }}</span
            >
            <br />可售数量：
            <span style="color: red"
              >{{ goodsDetail.saleInfo.amountOnSale
              }}{{ goodsDetail.saleInfo.unit }}</span
            >
            <br />厂货通渠道专享价（如果存在即包邮）：
            <span style="color: red"
              >¥ {{ goodsDetail.saleInfo.channelPrice }}</span
            >
            <br />是否支持网上交易：
            <span style="color: red">{{
              goodsDetail.saleInfo.supportOnlineTrade ? "是" : "否"
            }}</span>
            <br />运费：
            <!-- <span style="color: red">¥ {{ charge.area[0][1] }}</span> -->
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col>
            特殊区域（默认一件邮费）：<span
              v-for="(item, index) in charge.area"
              :key="index"
            >
              <p>{{ item[0] + ":" + item[1] }}元</p>
            </span>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row :gutter="20">
          数量：
          <el-input-number
            v-model="form.total"
            :min="1"
            :max="999"
            label="数量"
          ></el-input-number>
          <el-button type="primary" @click="to1688">查看1688官网商品</el-button>
          <el-button type="primary" @click="dialogVisible = true"
            >添加我的商品库</el-button
          >
          <span
            >¥：{{
              form.total * goodsDetail.skuInfos[form.edu].consignPrice
            }}</span
          >
        </el-row>
        <el-divider></el-divider>
        <el-row :gutter="20">
          <el-col
            :span="6"
            v-for="(item, index) in goodsDetail.attributes"
            :key="index"
            >{{ item.attributeName }} : {{ item.value }}</el-col
          >
        </el-row>
      </el-col>
    </el-row>
    <el-divider></el-divider>
    <el-row v-html="goodsDetail.description"></el-row>
    <el-dialog title="添加" :visible.sync="dialogVisible" width="95%">
      <span>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>1688</span>
              </div>
              <div class="text item">
                <el-collapse v-model="activeNames">
                  <el-collapse-item title="品名" name="1">{{
                    absGoodsDetail.subject
                  }}</el-collapse-item>
                  <el-collapse-item title="sku" name="2">
                    <el-row>
                      <el-col
                        :span="24"
                        v-for="(item, index) in absGoodsDetail.skuInfos"
                        :key="index"
                      >
                        <span v-for="(i, index) in item.attributes" :key="index"
                          >{{ i.attributeName }} :
                          {{ i.attributeValue }}&#8195;</span
                        >
                        价格：{{ item.consignPrice }}&#8195;
                      </el-col>
                    </el-row>
                  </el-collapse-item>
                  <el-collapse-item title="头图" name="3">
                    <el-image
                      v-for="(item, index) in absGoodsDetail.image.images"
                      :key="index"
                      :src="item"
                      style="width: 100px; height: 100px"
                    />
                  </el-collapse-item>
                  <el-collapse-item title="单价" name="4"
                    >{{ absGoodsDetail.referencePrice }} 元</el-collapse-item
                  >
                  <el-collapse-item title="详细" name="5">
                    <el-row :gutter="20">
                      <el-col
                        :span="12"
                        v-for="(item, index) in absGoodsDetail.attributes"
                        :key="index"
                        >{{ item.attributeName }} : {{ item.value }}</el-col
                      >
                    </el-row>
                  </el-collapse-item>
                  <el-collapse-item title="详情图片" name="6">
                    <ul
                      class="infinite-list"
                      v-infinite-scroll="load"
                      style="overflow: auto"
                    >
                      <li
                        v-for="(item, index) in absForm.imageUrl"
                        :key="index"
                        class="infinite-list-item"
                      >
                        <el-image
                          :src="item"
                          alt="详情图"
                          style="width: 400px"
                        />
                        <span>{{ item }}</span>
                      </li>
                    </ul>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>字节</span>
              </div>
              <div class="text item">
                <el-collapse v-model="activeTt">
                  <el-collapse-item title="品名" name="1">
                    <el-input
                      v-model="goodsDetail.subject"
                      :value="goodsDetail.subject"
                      placeholder="品名"
                    ></el-input>
                  </el-collapse-item>
                  <el-collapse-item title="sku" name="2">
                    <el-button
                      type="primary"
                      icon="el-icon-box"
                      @click="cheackAll"
                      style="width: 45%; margin-bottom: 20px"
                      >全选</el-button
                    >
                    <el-button
                      type="primary"
                      icon="el-icon-box"
                      @click="skuChecked = []"
                      style="width: 45%; margin-bottom: 20px"
                      >取消全选</el-button
                    >
                    <el-checkbox-group v-model="skuChecked">
                      <el-checkbox
                        v-for="item in goodsDetail.skuInfos"
                        :key="item.specId"
                        :label="item.specId"
                      >
                        <div
                          v-for="(i, index) in item.attributes"
                          :key="index"
                          style="display: flex"
                        >
                          <p class="attrName">{{ i.attributeName }}</p>
                          <el-input
                            type="textarea"
                            :autosize="{ minRows: 1, maxRows: 4 }"
                            v-model="i.attributeValue"
                          />
                          <p class="attrName">价格：</p>
                          <el-input
                            type="textarea"
                            :autosize="{ minRows: 1, maxRows: 4 }"
                            v-model="item.consignPrice"
                          />
                        </div>
                      </el-checkbox>
                    </el-checkbox-group>
                    <el-divider></el-divider>sku 添加：
                    <el-row>
                      <el-col :span="20">
                        <el-row v-for="(item, index) in total" :key="index">
                          <el-col :span="8">
                            <el-select
                              v-model="addSku.specId[index]"
                              placeholder="请选择"
                              @change="skuAdd"
                            >
                              <el-option
                                v-for="(item, index) in absGoodsDetail.skuInfos"
                                :key="index"
                                :label="
                                  item.attributes[0].attributeName +
                                  ':' +
                                  item.attributes[0].attributeValue +
                                  (item.attributes.length > 1
                                    ? item.attributes[1].attributeName +
                                      ':' +
                                      item.attributes[1].attributeValue
                                    : '')
                                "
                                :value="item.specId"
                              >
                                <span
                                  v-for="(i, index) in item.attributes"
                                  :key="index"
                                  >{{ i.attributeName }}:{{
                                    i.attributeValue
                                  }}</span
                                >
                                <span>价格：{{ item.consignPrice }}</span>
                              </el-option>
                            </el-select>
                          </el-col>
                          <el-col
                            :span="8"
                            v-for="(item, ind) in absGoodsDetail.skuInfos[0]
                              .attributes"
                            :key="ind"
                          >
                            <el-input
                              v-model="addSku.desc[index][ind]"
                              :placeholder="item.attributeName"
                            />
                          </el-col>
                          <el-col :span="4">
                            <el-input
                              type="number"
                              v-model="addSku.price[index]"
                              placeholder="价格"
                            />
                          </el-col>
                        </el-row>
                      </el-col>
                      <el-col :span="4">
                        <el-button
                          type="primary"
                          icon="el-icon-circle-plus"
                          @click="totalAdd"
                        ></el-button>
                        <br />
                        <el-button
                          type="primary"
                          icon="el-icon-remove"
                          @click="totalRemove"
                        ></el-button>
                      </el-col>
                    </el-row>
                  </el-collapse-item>
                  <el-collapse-item title="头图" name="3">
                    <el-row>
                      <el-col
                        :span="24"
                        v-for="(item, index) in goodsDetail.image.images"
                        :key="index"
                      >
                        <el-image
                          :src="item"
                          style="width: 100px; height: 100px"
                          alt="不加载"
                        />
                        <el-input
                          v-model="goodsDetail.image.images[index]"
                          :value="item"
                          placeholder="头图"
                        ></el-input>
                      </el-col>
                    </el-row>
                  </el-collapse-item>
                  <el-collapse-item title="单价" name="4">
                    <el-input
                      v-model="goodsDetail.referencePrice"
                      :value="goodsDetail.referencePrice"
                    ></el-input>
                  </el-collapse-item>
                  <el-collapse-item title="详细" name="5">
                    <el-row :gutter="20">
                      <el-col
                        :span="12"
                        v-for="(item, index) in goodsDetail.attributes"
                        :key="index"
                        >{{ item.attributeName }} : {{ item.value }}</el-col
                      >
                    </el-row>
                  </el-collapse-item>
                  <el-collapse-item title="详情图片" name="6">
                    <ul
                      class="infinite-list"
                      v-infinite-scroll="load"
                      style="overflow: auto"
                    >
                      <li
                        v-for="(item, index) in form.imageUrl"
                        :key="index"
                        class="infinite-list-item"
                      >
                        <el-image
                          :src="item"
                          alt="详情图"
                          style="width: 400px"
                        />
                        <el-input
                          v-model="form.imageUrl[index]"
                          :value="item"
                          placeholder="详情图"
                        ></el-input>
                      </li>
                    </ul>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="toTt">添加</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import bind from "@/components/Bind.vue";
export default {
  name: "shopDetail",
  data() {
    return {
      charge: { value: "计算中", area: [] },
      dialogVisible: false,
      form: { edu: 0, total: 1, imageUrl: [] },
      absForm: { edu: 0, total: 1, imageUrl: [] },
      formOffer: {
        accessToken: "",
        offerId: "",
      },
      goodsDetail: {},
      absGoodsDetail: {},
      activeNames: ["0"],
      activeTt: ["0"],
      skuChecked: [],
      total: 0,
      addSku: { specId: [], desc: [[]], price: [], skuId: [] },
    };
  },
  methods: {
    cheackAll() {
      let skuInfos = this.goodsDetail.skuInfos;
      if (skuInfos.length > this.skuChecked.length) {
        skuInfos.forEach((item) => {
          let specId = item.specId;
          if (this.skuChecked.indexOf(specId) == -1) {
            this.skuChecked.push(specId);
          }
        });
      } else {
        this.$message({ message: "已经全选", type: "warning" });
      }
    },
    getCharge() {
      let chargeInfo = this.absGoodsDetail.shippingInfo;
      let unitWeight = chargeInfo.unitWeight * 1000;
      console.log(unitWeight);
      if (
        chargeInfo.freightTemplateID == 0 ||
        chargeInfo.freightTemplateID == 1
      ) {
        chargeInfo.freightTemplateID == 0
          ? (this.charge.value = "买卖双方协商运费，结算时填写协商后的运费")
          : (this.charge.value = "包邮");
      } else {
        chargeInfo.freightTemplate.forEach((element, index) => {
          if (element.expressSubTemplate.subTemplateDTO.chargeType == 0) {
            // console.log('with weight');
            element.expressSubTemplate.rateList.forEach((item, ind) => {
              if (
                item.toAreaCodeText !== null &&
                item.toAreaCodeText != undefined
              ) {
                let firstUnit = item.rateDTO.firstUnit;
                let firstUnitFee = item.rateDTO.firstUnitFee;
                let nextUnit = item.rateDTO.nextUnit;
                let nextUnitFee = item.rateDTO.nextUnitFee;
                let total =
                  firstUnitFee +
                  ((this.absGoodsDetail.shippingInfo.unitWeight * 1000 -
                    firstUnit) /
                    nextUnit) *
                    nextUnitFee;
                if (
                  this.absGoodsDetail.shippingInfo.unitWeight * 1 <=
                  firstUnit
                ) {
                  total = firstUnitFee;
                }
                this.charge.area.push([item.toAreaCodeText, total / 100]);
              }
            });
          } else {
            // console.log('with count');
            element.expressSubTemplate.rateList.forEach((item, ind) => {
              if (item.toAreaCodeText != null) {
                let firstUnit = item.rateDTO.firstUnit;
                let firstUnitFee = item.rateDTO.firstUnitFee;
                let nextUnit = item.rateDTO.nextUnit;
                let nextUnitFee = item.rateDTO.nextUnitFee;
                let total = 0;
                if (firstUnit >= 1) {
                  total = firstUnitFee;
                } else {
                  total =
                    firstUnitFee + ((1 - firstUnit) / nextUnit) * nextUnitFee;
                }
                this.charge.area.push([item.toAreaCodeText, total / 100]);
              }
            });
          }
        });
      }
    },
    to1688() {
      window.location.href = `https://detail.1688.com/offer/${this.$route.params.id}.html?spm=a260j.12536015.jr601u7p.1.b9fc700evMkAcK`;
    },
    totalAdd() {
      this.addSku.desc.push([]);
      this.total++;
    },
    totalRemove() {
      this.addSku.desc.pop();
      this.total--;
    },
    async getDetail() {
      this.formOffer.offerId = this.$route.params.id;
      await this.$http
        .post(`/goods/detail`, this.formOffer)
        .then((response) => {
          this.absGoodsDetail = JSON.parse(response.data.message).productInfo;
          this.goodsDetail = JSON.parse(response.data.message).productInfo;
          this.getCharge();
          if (this.goodsDetail.skuInfos == null) {
            this.absGoodsDetail["skuInfos"] = [
              {
                amountOnSale: 0,
                attributes: [
                  {
                    attributeID: 3216,
                    attributeName: "备注",
                    attributeValue: "默认",
                    skuImageUrl: this.absGoodsDetail.image.images[0],
                  },
                ],
                cargoNumber: "BA-16L-01",
                consignPrice: this.absGoodsDetail.saleInfo.consignPrice,
                price: this.absGoodsDetail.saleInfo.consignPrice,
                skuId: 4257282313344,
                specId: "455a0c364fc4b4f9f3d2dd85f14dd7ba",
              },
            ];
            this.goodsDetail["skuInfos"] = [
              {
                amountOnSale: 0,
                attributes: [
                  {
                    attributeID: 3216,
                    attributeName: "备注",
                    attributeValue: "默认",
                    skuImageUrl: this.absGoodsDetail.image.images[0],
                  },
                ],
                cargoNumber: "BA-16L-01",
                consignPrice: this.absGoodsDetail.saleInfo.consignPrice,
                price: this.absGoodsDetail.saleInfo.consignPrice,
                skuId: 4257282313344,
                specId: "455a0c364fc4b4f9f3d2dd85f14dd7ba",
              },
            ];
          }
          this.getImageUrl();
        })
        .catch((err) => {
          this.$message({
            message: "商品不存在【" + err + "】",
            type: "warning",
          });
        });
    },
    async toTt() {
      this.dialogVisible = false;
      let sku = [];
      let skuChild = {
        specId: "",
        consignPrice: "",
        price: "",
        attributes: [],
      };
      this.goodsDetail.skuInfos.forEach((item, index) => {
        if (this.skuChecked.indexOf(item.specId) > -1) {
          sku.push(item);
        }
      });
      this.addSku.specId.forEach((item, index) => {
        skuChild.specId = this.addSku.specId[index];
        skuChild.price = this.addSku.price[index];
        skuChild.consignPrice = this.addSku.price[index];
        for (var i = 0; i < this.addSku.desc[0].length; i++) {
          skuChild.attributes.push({ attributeName: "", attributeValue: "" });
        }
        skuChild.attributes.forEach((ite, indexChild) => {
          ite.attributeName = this.absGoodsDetail.skuInfos[0].attributes[
            indexChild
          ].attributeName;
          ite.attributeValue = this.addSku.desc[index][indexChild];
        });
        sku.push(skuChild);
        skuChild = {
          specId: "",
          consignPrice: "",
          price: "",
          attributes: [],
        };
      });
      let csku = [];
      sku.forEach((item) => {
        csku.push({
          specId: item.specId,
          skuId: item.skuId,
          offerId: this.$route.params.id,
        });
      });
      // 添加cSku
      await this.$http
        .post(`/bind/add/goods/bind`, csku)
        .then((res) => {
          let listSpecId = res.data.dataMap.data;
          sku.forEach((item, index) => {
            item.skuId = listSpecId[index];
          });
          this.goodsDetail.skuInfos = sku;
          this.goodsDetail.description = this.form.imageUrl;
          let values = Object.values(this.goodsDetail);
          setTimeout(() => {
            let upload = {};
            Object.keys(this.goodsDetail).forEach((key, index) => {
              upload[key] = JSON.stringify(values[index]);
            });
            upload["offerId"] = this.formOffer.offerId;
            this.$http
              .post(`/goods/add-goods`, upload)
              .then((response) => {
                if (response.data.code == 200) {
                  this.$message({ message: "上架成功！", type: "success" });
                } else {
                  this.$message({
                    message: response.data.message,
                    type: "warning",
                  });
                }
                this.$router.push({ path: "/1688/library" });
              })
              .catch((err) => {
                this.$message({ message: "网络错误", type: "warning" });
              });
          }, 500);
        })
        .catch((err) => {
          this.$message({ message: "网络错误", type: "warning" });
        });
    },
    async getImageUrl() {
      await this.$http
        .post(`/ali/get-img`, {
          resources: this.goodsDetail.description,
        })
        .then((response) => {
          this.form.imageUrl = response.data.dataMap.data;
          this.absForm = JSON.parse(JSON.stringify(this.form));
        });
    },
    load() {
      console.log();
    },
    skuAdd(item) {
      console.log(item);
    },
  },
  components: { bind },
  created() {
    this.getDetail();
  },
};
</script>

<style scoped>
.infinite-list {
  width: 400px;
  height: 600px;
  line-height: 40px;
  margin: 10px;
  overflow: auto;
}
li {
  list-style-type: none;
}
.attrName {
  width: 150px;
  float: left;
  margin-left: 10px;
}
</style>
